﻿using AutoMapper;
using MediatR;
using S.Common.EditWanderStateHelper;
using S.Common.helper;
using S.EliminationOrDath.API.Application.Command.EOrDCommand;
using S.EliminationOrDath.API.Dtos;
using S.EliminationOrDath.Domain;
using S.EliminationOrDath.Domain.Models;
using S.EliminationOrDath.Infrastructure.Interface;
using static S.EliminationOrDath.API.Application.Command.EOrDCommand.EliminationCommand;

namespace S.EliminationOrDath.API.Application.CommandHandlers.EOrDCommandHandler
{
    /// <summary>
    /// 中介者方法实现类--淘汰
    /// </summary>
    public class EliminationCommandHandler : IRequestHandler<AddsEliminationCommand, bool>, IRequestHandler<ExamineStatusCommand, int>, IRequestHandler<UpdEliminationCommand, bool>, IRequestHandler<DelEliminationCommand, bool>
    {
        private readonly IEliminationRepository er;
        private readonly IMapper mapper;
        private readonly EliminationDbContext db;
        private readonly IConfiguration configuration;
        private readonly IHttpContextAccessor httpContextAccessor;

        public EliminationCommandHandler(IEliminationRepository er, IMapper mapper, EliminationDbContext db, IConfiguration configuration, IHttpContextAccessor httpContextAccessor)
        {
            this.er = er;
            this.mapper = mapper;
            this.db = db;
            this.configuration = configuration;
            this.httpContextAccessor = httpContextAccessor;
        }

        #region 实现方法

        /// <summary>
        /// 批量添加淘汰表数据
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<bool> Handle(AddsEliminationCommand? request, CancellationToken cancellationToken)
        {
            List<EliminationModel?>? em = new List<EliminationModel?>();
            em = mapper.Map<List<EliminationModel?>?>(request.eliminations);
            return await er.AddRange(em);
        }
        /// <summary>
        /// 批量审批 0审批失败，1审批成功，2取消审批成功
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<int> Handle(ExamineStatusCommand request, CancellationToken cancellationToken)
        {
            List<EliminationModel> ems = new List<EliminationModel>();
            //转换为model
            ems = mapper.Map<List<EliminationModel>>(request.eliminationDtos);
            if (ems.Count() == 0)
            {
                return 0;
            }
            //判断上下架状态
            if (request.onShelf)
            {
                //实例化列表
                List<WanderStateDynamicEditPLDto> Status = new List<WanderStateDynamicEditPLDto>();
                List<PresentStatePLDto> FileUpdateStatePLs = new List<PresentStatePLDto>();
                SheepTransFersDto sheepTransFersDto = new SheepTransFersDto();
                List<sheep> stfds = new List<sheep>();
                var con = 0;
                //循环淘汰列表中的值
                foreach (var eliminationModel in ems)
                {
                    if (eliminationModel.DepartureState)
                    {
                        //实例化类
                        WanderStateDynamicEditPLDto statu = new WanderStateDynamicEditPLDto();
                        PresentStatePLDto fus = new PresentStatePLDto();
                        //查询转舍前档案中的状态
                        var gss = GetSheepState(eliminationModel.EarTag, configuration).FirstOrDefault(m => m.EarTag == eliminationModel.EarTag);
                        //把对应的耳号和审批前的信息放入对应的变量
                        statu.earTag = eliminationModel.EarTag;
                        statu.wanderReproductiveState = eliminationModel.ustate;
                        fus.earTag = eliminationModel.EarTag;
                        fus.presenceState = eliminationModel.SheepStatuss;
                        #region 添加转舍数据
                        //转入栋舍
                        var HouseIdTransfer = GetHouse(eliminationModel.TurnOutBuild, configuration).value;
                        //转入栏位
                        var FieldIdTransfer = GetField(eliminationModel.TurnOutHuts, configuration).value;
                        //转出栋舍
                        var HouseId = GetHouse(eliminationModel.ShiftToBuild, configuration).value;
                        //转出栏位
                        var FieldId = GetField(eliminationModel.ShiftToHuts, configuration).value;

                        sheep stfd = new sheep();

                        stfd.EarTag = eliminationModel.EarTag;
                        //转入
                        stfd.ShiftToBuild = HouseIdTransfer;
                        stfd.ShiftToHuts = FieldIdTransfer;
                        stfd.ShiftToBuildingManagementId = HouseIdTransfer;
                        stfd.ShiftToColumnManagementId = FieldIdTransfer;
                        //转出
                        stfd.TurnOutBuild = HouseId;
                        stfd.TurnOuBuildingManagementId = HouseId;
                        stfd.TurnOuColumnManagementId = FieldId;
                        stfd.TurnOutHuts = FieldId;
                        //转舍日期
                        stfd.SurrenderDate = eliminationModel.PhaseOutDate;
                        stfd.CreateDate = DateTime.Now;

                        stfd.RoundType = 15;

                        stfds.Add(stfd);

                        #endregion
                        //修改状态为未离场
                        eliminationModel.DepartureState = false;
                        eliminationModel.UpdateBy = request.UserName;
                        eliminationModel.UpdateDate = DateTime.Now;
                        eliminationModel.Reviewer = request.UserName;
                        eliminationModel.ReviewTime = DateTime.Now;
                        //放入列表中
                        Status.Add(statu);
                        FileUpdateStatePLs.Add(fus);
                    }
                }
                sheepTransFersDto.sheep = stfds;
                //执行对应的方法
                SheepStatus(Status,configuration);
                SheepFileUpdateStatePLs(FileUpdateStatePLs, configuration);
                SheepSheds(sheepTransFersDto,configuration);
                //返回修改后的判断
                if (!await er.UpdateRange(ems))
                {
                    return 0;
                }
                return 2;
            }
            else
            {
                //实例化列表
                List<WanderStateDynamicEditPLDto> Status = new List<WanderStateDynamicEditPLDto>();
                List<PresentStatePLDto> FileUpdateStatePLs = new List<PresentStatePLDto>();
                SheepTransFersDto? sheepTransFersDto = new SheepTransFersDto();
                List<sheep> stfds = new List<sheep>();
                var con = 0;
                //循环淘汰列表中的值
                foreach (var eliminationModel in ems)
                {
                    //实例化类
                    WanderStateDynamicEditPLDto statu = new WanderStateDynamicEditPLDto();
                    PresentStatePLDto fus = new PresentStatePLDto();
                    //查询转舍前档案中的状态
                    var gss = GetSheepState(eliminationModel.EarTag,configuration).FirstOrDefault(m=>m.EarTag == eliminationModel.EarTag);
                    //修改为淘汰状态
                    statu.earTag = eliminationModel.EarTag;
                    statu.wanderReproductiveState = 8;
                    fus.earTag = eliminationModel.EarTag;
                    fus.presenceState = 5;
                    //放入对应的变量中
                    eliminationModel.ustate = (int)gss.WanderReproductiveState;
                    eliminationModel.SheepStatuss = (int)gss.PresenceState;
                    #region 添加转舍数据
                    //转入栋舍
                    var HouseIdTransfer = GetHouse(eliminationModel.ShiftToBuild, configuration).value;
                    //转入栏位
                    var FieldIdTransfer = GetField(eliminationModel.ShiftToHuts, configuration).value;
                    //转出栋舍
                    var HouseId = GetHouse(eliminationModel.TurnOutBuild, configuration).value;
                    //转出栏位
                    var FieldId = GetField(eliminationModel.TurnOutHuts, configuration).value;

                    sheep stfd = new sheep();

                    stfd.EarTag = eliminationModel.EarTag;
                    //转入
                    stfd.ShiftToBuild = HouseIdTransfer;
                    stfd.ShiftToHuts = FieldIdTransfer;
                    stfd.ShiftToBuildingManagementId = HouseIdTransfer;
                    stfd.ShiftToColumnManagementId = FieldIdTransfer;
                    //转出
                    stfd.TurnOutBuild = HouseId;
                    stfd.TurnOuBuildingManagementId = HouseId;
                    stfd.TurnOuColumnManagementId = FieldId;
                    stfd.TurnOutHuts = FieldId;
                    //转舍日期
                    stfd.SurrenderDate = eliminationModel.PhaseOutDate;
                    stfd.CreateDate = DateTime.Now;

                    stfd.RoundType = 15;

                    stfds.Add(stfd);

                    #endregion
                    //把状态改为离场
                    eliminationModel.DepartureState = true;
                    eliminationModel.UpdateBy = request.UserName;
                    eliminationModel.UpdateDate = DateTime.Now;
                    eliminationModel.Reviewer = request.UserName;
                    eliminationModel.ReviewTime = DateTime.Now;
                    //把值添加到对应的列表
                    Status.Add(statu);
                    FileUpdateStatePLs.Add(fus);
                }
                sheepTransFersDto.sheep = stfds;
                //执行对应的方法
                SheepStatus(Status, configuration);
                SheepFileUpdateStatePLs(FileUpdateStatePLs, configuration);
                SheepSheds(sheepTransFersDto,configuration);
                //返回修改后的判断
                if (!await er.UpdateRange(ems))
                {
                    return 0;
                }
                return 1;
            }
        }
        /// <summary>
        /// 修改淘汰表数据
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<bool> Handle(UpdEliminationCommand request, CancellationToken cancellationToken)
        {
            EliminationModel? em = new EliminationModel();
            em = mapper.Map<EliminationModel>(request.eliminationDtos);
            return await er.Update(em);
        }
        /// <summary>
        /// 批量删除淘汰数据
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<bool> Handle(DelEliminationCommand request, CancellationToken cancellationToken)
        {
            string[] strings = request.ids.Split(',');
            List<EliminationModel>? em = new List<EliminationModel>();
            foreach (string s in strings) 
            {
                var list = (await er.GetAll()).FirstOrDefault(m => m.EliminationId == Convert.ToInt32(s));
                em.Add(list);
            }
            return await er.DeleteRange(em);
        }
        #endregion

        #region 封装调用方法

        /// <summary>
        /// 批量修改羊只状态
        /// </summary>
        /// <returns></returns>
        private static string SheepStatus(List<WanderStateDynamicEditPLDto> dto, IConfiguration configuration)
        {
            var conf = configuration.GetValue<string>("WebApiIp");
            return HttpClientHelper.PutDataResponse(conf + "/achs/api/Wander/WanderStateDynamicEditPL", dto);
        }
        /// <summary>
        /// 批量修改在场状态
        /// </summary>
        /// <returns></returns>
        private static string SheepFileUpdateStatePLs(List<PresentStatePLDto> dto, IConfiguration configuration)
        {
            var conf = configuration.GetValue<string>("WebApiIp");
            return HttpClientHelper.PutDataResponse(conf + "/achs/api/SheepFileModel/PresentStatePL", dto);
        }
        /// <summary>
        /// 羊只批量转舍
        /// </summary>
        /// <returns></returns>
        private static string SheepSheds(SheepTransFersDto dto, IConfiguration configuration)
        {
            var conf = configuration.GetValue<string>("WebApiIp");
            return HttpClientHelper.PostResponse(conf + "/transset/api/TransFer/CreateSheepTransFers", dto); 
        }
        /// <summary>
        /// 显示耳号信息
        /// </summary>
        /// <returns></returns>
        private static List<SheepTypeDto> GetSheepState(string ear, IConfiguration configuration)
        {
            var conf = configuration.GetValue<string>("WebApiIp");
            return HttpClientHelper.GetResponseList<SheepTypeDto>(conf + "/ach/api/SheepFileModel/GetSheepFilesByEarTag?EarTag=" + ear);
        }
        /// <summary>
        /// 显示栋舍信息
        /// </summary>
        /// <returns></returns>
        private static HouseFieldDto GetHouse(string name,IConfiguration configuration)
        {
            var conf = configuration.GetValue<string>("WebApiIp");
            return HttpClientHelper.GetResponseList<HouseFieldDto>(conf + "/Authorization/api/ColumnManagement/GetColumnList").FirstOrDefault(m=>m.label == name);
        }
        /// <summary>
        /// 显示栏位信息
        /// </summary>
        /// <returns></returns>
        private static HouseFieldDto GetField(string name, IConfiguration configuration)
        {
            var conf = configuration.GetValue<string>("WebApiIp");
            return HttpClientHelper.GetResponseList<HouseFieldDto>(conf + "/Authorization/api/ColumnManagement/GetFieldMode").FirstOrDefault(m => m.label == name);
        }

        #endregion
    }
}
